<template>
  <div class="app-container">
    <span v-if="showConfig">
      <el-empty
        description="暂未开通"
        v-if="!productCategoryUrl"></el-empty>
      <span v-else>
        <component
          v-bind:is="productComponent"
          ref="products"
          :userProductDetail.sync="userProductDetail"></component>
      </span>
    </span>
  </div>
</template>
<script>
import { getUserProductDetail, updateUserProductConfig } from '@/api/user';
import { productConfigListOptions } from './data';
export default {
  name: 'config',
  props: {
    userProductId: {
      type: [String, Number],
      default: 0,
    },
  },
  watch: {
    userProductId: {
      handler(value) {
        this.getDetail(value);
      },
      immediate: true,
    },
  },
  data() {
    return {
      productCategoryUrl: null,
      userProductDetail: null,
      showConfig: false
    };
  },
  computed: {
    // 产品组件
    productComponent() {
      if (this.productCategoryUrl == null) {
        return '';
      }
      return resolve => {
        require(['@/views/user/product/components/' + this.productCategoryUrl + '.vue'], resolve);
      };
    },
  },
  methods: {
    async getDetail(value) {
      if (value > 0) {
        getUserProductDetail({ id: value })
          .then(res => {
            this.$set(this, 'showConfig', true);
            this.$set(this, 'userProductDetail', res.data);
            if (res.data && res.data.product && res.data.product.category) {
              this.checkCategoryConfig(res.data.product.category.label);
            }
          })
          .catch(() => {
            this.$set(this, 'showConfig', true);
          });
      } else {
        this.$set(this, 'showConfig', true);
      }
    },
    checkCategoryConfig(categoryLabel) {
      let filterLabel = productConfigListOptions.find(el => el.label == categoryLabel);
      if (filterLabel) {
        this.$set(this, 'productCategoryUrl', filterLabel.route);
      }
    },
    handleSubmit() {
      if( !this.$refs.products ){
        this.$emit('update:loadingButton', ['submit']);
        this.$emit('update:loadingButton', []);
        this.$emit('update:visible', false);
      } else {
        let configValue = this.$refs.products.getConfigValue()
        if( configValue ){
          this.$emit('update:loadingButton', ['submit']);
          updateUserProductConfig({ id: this.userProductDetail.id, config: configValue }).then(()=>{
            this.$emit('update:loadingButton', []);
            this.$emit('update:visible', false);
          }).catch(()=>{
            this.$emit('update:loadingButton', []);
          })
        }
      }
    },
  },
};
</script>
